import {
  Body,
  Controller,
  Delete,
  Get,
  Param,
  Post,
  Put,
} from '@nestjs/common';
import { User } from './user.interface';
import { UserService } from './user.service';
import { CreateUserDTO, EditUserDTO, SelectUserDto } from './user.dto';
import { ApiOperation, ApiTags } from '@nestjs/swagger';

interface UserResponse<T = unknown> {
  code: number;
  data?: T;
  message: string;
}

@ApiTags('用户接口')
@Controller('user')
export class UserController {
  constructor(private readonly userService: UserService) {}
  @Get('getUserList')
  async findAll(): Promise<UserResponse<User[]>> {
    return {
      code: 200,
      data: await this.userService.findAll(),
      message: 'success',
    };
  }

  @Get('getUserById/:_id')
  async findOne(@Param('_id') _id: string): Promise<UserResponse<User>> {
    return {
      code: 200,
      data: await this.userService.findOne(_id),
      message: 'success',
    };
  }

  @Post('add')
  async addOne(@Body() body: CreateUserDTO): Promise<UserResponse> {
    await this.userService.addOne(body);
    return {
      code: 200,
      message: 'success',
    };
  }

  @Put('update/:_id')
  async editOne(
    @Param('_id') _id: string,
    @Body() body: EditUserDTO,
  ): Promise<UserResponse> {
    await this.userService.editOne(_id, body);
    return {
      code: 200,
      message: 'success',
    };
  }

  @Delete('delete/:_id')
  async deleteOne(@Param('_id') _id: string): Promise<UserResponse> {
    await this.userService.deleteOne(_id);
    return {
      code: 200,
      message: 'success',
    };
  }

  @Post('findPage')
  @ApiOperation({
    tags: ['分页查询'],
    description: '分页查询接口',
  })
  async findPageList(@Body() body: SelectUserDto): Promise<{
    code: number;
    data: { total: number; totalSize: number; list: User[] };
    message: string;
  }> {
    const userList = await this.userService.findPage(
      body.pageNum,
      body.pageSize,
    );
    const count = await this.userService.findCount();
    const totalSize = await this.getTotalPages(count, body.pageSize);
    return {
      code: 200,
      data: { list: userList, total: count, totalSize: totalSize },
      message: 'success',
    };
  }

  private async getTotalPages(count: number, pageSize: number) {
    return Math.ceil(count / pageSize);
  }
}
